package com.mathmodeling.controller;

import com.mathmodeling.dto.ApiResponse;
import com.mathmodeling.entity.Contest;
import com.mathmodeling.entity.Topic;
import com.mathmodeling.repository.ContestRepository;
import com.mathmodeling.repository.TopicRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDate;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/admin")
public class AdminController {
    
    @Autowired
    private ContestRepository contestRepository;
    
    @Autowired
    private TopicRepository topicRepository;
    
    @Value("${file.upload.path}")
    private String uploadPath;
    
    @Value("${file.upload.topic}")
    private String topicPath;
    
    /**
     * 创建竞赛 - 严格按照API文档规范
     */
    @PostMapping("/contests")
    public ApiResponse<ContestResponse> createContest(@RequestParam String title,
                                           @RequestParam String startTime,
                                           @RequestParam String endTime,
                                           @RequestParam(value = "topics", required = false) MultipartFile[] topicFiles,
                                           @RequestParam(value = "remarks", required = false) String[] remarks,
                                           @RequestParam(value = "names", required = false) String[] names) {
        try {
            // 验证必需参数
            if (title == null || title.trim().isEmpty()) {
                return ApiResponse.error(400, "竞赛标题不能为空");
            }
            
            if (startTime == null || startTime.trim().isEmpty()) {
                return ApiResponse.error(400, "开始时间不能为空");
            }
            
            if (endTime == null || endTime.trim().isEmpty()) {
                return ApiResponse.error(400, "结束时间不能为空");
            }
            
            // 验证日期格式
            LocalDate startDate, endDate;
            try {
                startDate = LocalDate.parse(startTime.trim());
                endDate = LocalDate.parse(endTime.trim());
            } catch (Exception e) {
                return ApiResponse.error(400, "日期格式错误，请使用YYYY-MM-DD格式");
            }
            
            // 验证日期逻辑
            if (startDate.isAfter(endDate)) {
                return ApiResponse.error(400, "开始时间不能晚于结束时间");
            }
            
            if (startDate.isBefore(LocalDate.now())) {
                return ApiResponse.error(400, "开始时间不能早于今天");
            }
            
            // 创建竞赛
            Contest contest = new Contest();
            contest.setId(UUID.randomUUID().toString());
            contest.setTitle(title.trim());
            contest.setStartTime(startDate);
            contest.setEndTime(endDate);
            contest.setResultRelease(endDate.plusDays(7)); // 默认7天后公布结果
            
            contestRepository.save(contest);
            
            // 处理题目文件
            if (topicFiles != null && topicFiles.length > 0) {
                // 验证题目文件数量与名称数量是否匹配
                if (names == null || names.length != topicFiles.length) {
                    return ApiResponse.error(400, "题目文件数量与名称数量不匹配");
                }
                
                // 创建题目文件目录
                String topicDir = uploadPath + topicPath;
                File topicDirFile = new File(topicDir);
                if (!topicDirFile.exists()) {
                    topicDirFile.mkdirs();
                }
                
                for (int i = 0; i < topicFiles.length; i++) {
                    MultipartFile topicFile = topicFiles[i];
                    String name = names[i];
                    String remark = (remarks != null && i < remarks.length) ? remarks[i] : "";
                    
                    // 验证题目名称
                    if (name == null || name.trim().isEmpty()) {
                        return ApiResponse.error(400, "题目名称不能为空");
                    }
                    
                    // 验证题目名称格式（A-E）
                    if (!name.matches("^[A-E]$")) {
                        return ApiResponse.error(400, "题目名称必须是A-E中的一个");
                    }
                    
                    // 验证文件格式
                    if (topicFile == null || topicFile.isEmpty()) {
                        return ApiResponse.error(400, "题目文件不能为空");
                    }
                    
                    String originalFilename = topicFile.getOriginalFilename();
                    if (originalFilename == null || !originalFilename.toLowerCase().endsWith(".pdf")) {
                        return ApiResponse.error(400, "题目文件必须是PDF格式");
                    }
                    
                    // 验证文件大小
                    if (topicFile.getSize() > 50 * 1024 * 1024) { // 50MB
                        return ApiResponse.error(400, "题目文件大小不能超过50MB");
                    }
                    
                    // 检查题目名称是否重复
                    if (topicRepository.existsByContestIdAndName(contest.getId(), name)) {
                        return ApiResponse.error(400, "题目名称 " + name + " 已存在");
                    }
                    
                    // 保存题目文件
                    String fileName = contest.getId() + "_" + name + ".pdf";
                    String filePath = topicDir + fileName;
                    File file = new File(filePath);
                    topicFile.transferTo(file);
                    
                    // 创建题目记录
                    Topic topic = new Topic();
                    topic.setId(UUID.randomUUID().toString());
                    topic.setContestId(contest.getId());
                    topic.setName(name);
                    topic.setDesc(getTopicDescription(name)); // 根据题目名称设置描述
                    topic.setFilePath(filePath);
                    topic.setRemark(remark);
                    
                    topicRepository.save(topic);
                }
            }
            
            ContestResponse response = new ContestResponse();
            response.setContestId(contest.getId());
            response.setTitle(contest.getTitle());
            
            return ApiResponse.success("竞赛创建成功", response);
            
        } catch (Exception e) {
            return ApiResponse.error(500, "竞赛创建失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据题目名称获取描述
     */
    private String getTopicDescription(String name) {
        switch (name) {
            case "A": return "人工智能主题";
            case "B": return "大数据主题";
            case "C": return "物联网主题";
            case "D": return "区块链主题";
            case "E": return "其他主题";
            default: return "未知主题";
        }
    }
    
    /**
     * 获取所有竞赛
     */
    @GetMapping("/contests")
    public ApiResponse<List<Contest>> getAllContests() {
        try {
            List<Contest> contests = contestRepository.findAll();
            return ApiResponse.success("获取竞赛列表成功", contests);
        } catch (Exception e) {
            return ApiResponse.error(500, "获取竞赛列表失败: " + e.getMessage());
        }
    }
    
    // 响应类
    public static class ContestResponse {
        private String contestId;
        private String title;
        
        public String getContestId() { return contestId; }
        public void setContestId(String contestId) { this.contestId = contestId; }
        
        public String getTitle() { return title; }
        public void setTitle(String title) { this.title = title; }
    }
} 